//
//  ZYSystem.swift
//  KaKaWallet
//
//  Created by ifly on 2018/1/3.
//  Copyright © 2018年 ibendi. All rights reserved.
//

import UIKit
import QuartzCore


typealias ZYSystemPhoto = (_ kkImage:UIImage) ->Void

class ZYSystem: NSObject {
    
    private var kkGetOnePhote:ZYSystemPhoto?
    
    
    internal static let start = ZYSystem.init()
    
    
    /// 私有方法初始化UIImagePickerController
    ///
    /// - Parameter type: 类型
    private func initImagePic(_ type:UIImagePickerControllerSourceType){
        
        if !UIImagePickerController.isSourceTypeAvailable(type) {
            debugPrint("请在info.plst 文件添加权限")
            return
        }
        let kkPic = UIImagePickerController.init()
        kkPic.sourceType = type
        kkPic.delegate = self
        UIApplication.shared.keyWindow?.rootViewController?.present(kkPic, animated: true, completion: nil)
    }
    

    /// 从相册获取一张照片
    ///
    /// - Parameter kkImageCompletion: 取到的照片代码块
    func kkGetPickerPhoto(_ kkImageCompletion:@escaping (UIImage)->Void) -> Void {
        
        initImagePic(.photoLibrary)
        self.kkGetOnePhote = kkImageCompletion
    }
    
    
    /// 通过相机照相获取图片
    ///
    /// - Parameter kkImageCompletion: 取到的照片代码块
    func kkCameraPhoto(_ kkImageCompletion:@escaping (UIImage)->Void) -> Void {
        
        initImagePic(.photoLibrary)

        if kkGetOnePhote != nil{
            self.kkGetOnePhote = kkImageCompletion
        }
    }


}


extension ZYSystem:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
        
        picker.dismiss(animated: true, completion: nil)
        let img:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
       
        if kkGetOnePhote != nil{
            self.kkGetOnePhote!(img)
        }
        
    }
    
}
